package ThematicModelProto;

import java.util.ArrayList;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

public class Theme{
	
	private ArrayList<Theme> subthemes = new ArrayList<Theme>();
	private ArrayList<Motif> motifs = new ArrayList<Motif>();
	private String name;
	private String folder;
	
	
	
	public Theme(String name,String folder){
		this.folder = folder;
		String file = folder+name+".te";
		Document dom = Helpers.parseXmlFile(file);
		parseDocument(dom);
	}
	
	private void parseDocument(Document dom){
		//get the root element
		Element docEle = dom.getDocumentElement();
		
		name = docEle.getAttribute("name");
		
		//get a node list of  elements
		NodeList nl = docEle.getChildNodes();
	
		if(nl == null){return;}
	
		for(int i = 0 ; i < nl.getLength();i++) {
			Node el = nl.item(i);

			//required.addAll(loadComponents(el));
			loadComponents(el);
		}
	
	}
	
	public ArrayList<String> loadComponents(Node el){
		ArrayList<String> list = new ArrayList<String>();
		
		NodeList nl = el.getChildNodes();
		
		if(nl == null) {return list;}
		
		for(int i = 0 ; i < nl.getLength();i++) {
			Node n = nl.item(i);
			String nname = n.getNodeName();
			String value = n.getTextContent();
				
			if(nname=="theme-component"){
				subthemes.add(new Theme(value, folder));
			}else if(nname=="motif-component"){
				motifs.add(new Motif(value, folder));
			}else{continue;}
			
			
			list.add(value.toLowerCase());
			
		}
	
		return list;
		
	}

	public String getName(){
		return name;
	}
	
	public ArrayList<Theme> getThemes(ArrayList<Theme> allThemes){
		allThemes.add(this);//jussi might not like this
		for(int i=0; i < subthemes.size(); i++){
			subthemes.get(i).getThemes(allThemes);
		}
		return allThemes;
	}
	
	public ArrayList<Motif> getAllMotifs(ArrayList<Motif> allMotifs){
		allMotifs.addAll(this.motifs);
		for(int i=0; i < subthemes.size(); i++ ){
			subthemes.get(i).getAllMotifs(allMotifs);
		}
		return allMotifs;
	}

	public ArrayList<Motif> getChildMotifs(){
		return this.motifs;
	}
	
	public ArrayList<Theme> getChildThemes(){
		return this.subthemes;
	}
	
	/* Get motifs and the motifs of the first level themes for calculating coverage*/
	public ArrayList<Motif> getFirstLevelMotifs(ArrayList<Motif> firstMotifs){
		firstMotifs.addAll(this.motifs);
		for(Theme theme:this.subthemes){
			firstMotifs.addAll(theme.getChildMotifs());
		}
		return firstMotifs;
	}
	
}